<template>
  <div class="cart-wrapper">
    <ul v-for="item in state.list" :key="item.id">
      <li><img :src="item.img" alt="" /></li>
      <li>{{ item.goodsName }}</li>
      <li>
        <span class="base-btn" @click="handleToCart(item)">+</span>
      </li>
    </ul>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive } from 'vue'
import { useStore } from 'vuex'
import { CartItemType } from '../store'
import axios from 'axios'
const useEffectHome = (state: { list: CartItemType[] }) => {
  // 使用vuex仓库
  const store = useStore()
  const fetchCartList = async () => {
    const response = await axios.get('/cart.json').then()
    console.log('fetchCartList:', response.data)
    state.list = response.data
  }
  // 点击每一次，添加到vuex中
  const handleToCart = (item: CartItemType) => {
    store.commit('SET_CART_LIST', item)
  }

  return {
    fetchCartList,
    handleToCart
  }
}

export default defineComponent({
  setup() {
    const state = reactive({
      list: []
    })
    const { fetchCartList, handleToCart } = useEffectHome(state)
    onMounted(() => {
      fetchCartList()
    })
    return {
      state,
      handleToCart
    }
  }
})
</script>
<style lang="scss">
.base-btn {
  border-radius: 5px;
  cursor: pointer;
  width: 35px;
  height: 35px;
  font-size: 25px;
  text-align: center;
  line-height: 35px;
  padding: 5px;
  margin: 5px;
  background: lightcoral;
  color: white;
  display: inline-block;
}
</style>
